<?php

class event
{
	var $eid;					// Event ID.
	var $mul_db;				// Mullet DB connection.
	var $smf_db;				// SMF DB connection.

	// Event defaults.
	var $location =				'';
	var $created_by =			0;
	var $invite_time =			'';
	var $start_time =			'';
	var $isOpen =				TRUE;
	var $min_level =			0;
	var $cap =					0;
	var $limits =				array('mt' => 0, 'ot' => 0, 'hl' => 0, 'dm' => 0);
	var $slots =				array('mt' => 0, 'ot' => 0, 'hl' => 0, 'dm' => 0);
	var $mail_sent =			0;
	
	var $subscribers =			array();
	var $totals =				array();

	var $chars_not_subscribed = array();
	var $chars_subscribed =		array();





	// Constructor
	function event($mul_db, $smf_db, $event_id = NULL)
	{
		global $mConfig;


		$this->mul_db = $mul_db;
		$this->smf_db = $smf_db;

		$sub_totals = array_merge(array('total' => 0), $this->slots, array_fill_keys($mConfig['classes'], 0));
		$totals = array(
			'queue' => $sub_totals,
			'unavailable' => $sub_totals,
			'attending' => $sub_totals,
			'available' => $sub_totals,
			'subscribed' => $sub_totals);
		$this->totals = $totals;
		

		// Retrieve event information.
		if ($event_id != NULL)
		{
			$this->eid = $event_id;
			$this->getEvent();
		}
	}





	// Load event from database.
	function getEvent()
	{
		global $mConfig;


		$sql_query = 'SELECT * FROM '.$mConfig['table_events'].' WHERE event_id = '.$this->eid;
		$sql_result = mysql_query($sql_query, $this->mul_db) or die('There was an error querying the event from Mullet. SQL: '.$sql_query);
		
		$sql_fetch = mysql_fetch_assoc($sql_result);

		$this->created_by =			$sql_fetch['createdBy'];
		$this->location = 			$sql_fetch['location'];
		$this->invite_time =		$sql_fetch['invite_time'];
		$this->start_time =			$sql_fetch['start_time'];
		$this->isOpen =				$sql_fetch['isOpen'];
		$this->min_level =			$sql_fetch['min_level'];
		$this->cap =				$sql_fetch['cap'];
		$this->limits['mt'] =		$sql_fetch['mt'];
		$this->limits['ot'] =		$sql_fetch['ot'];
		$this->limits['hl'] =		$sql_fetch['hl'];
		$this->limits['dm'] =		$sql_fetch['dm'];
		$this->mail_sent =			$sql_fetch['mail_sent'];

		unset($sql_query); mysql_free_result($sql_result); unset($sql_fetch);
	}





	// Create or update an event.
	function setEvent($n_event)
	{
		global $mConfig;

		$errors = 0;


		// Strip input of code and trim whitespace.
		foreach ($n_event as $key => $value)
		{
			$n_event[$key] = sanatizeText($value);
			if ($n_event[$key] == '') $errors++;
		}

		// Check that values are numeric.
		foreach (array($n_event['mt'], $n_event['ot'], $n_event['hl'], $n_event['dm'], $n_event['min_level']) as $n)
		{
			if (!is_numeric($n)) $errors++;
		}

		// If any errors are found, cancel event creation.
		if ($errors > 0) return FALSE;


		// Create unix timestamp for invite and start time.
		$date = explode('-', $n_event['date']);
		$date = $date[1].'/'.$date[2].'/'.$date[0];

		$n_event['invite_time'] = strtotime($date.' '.date("g:i a", $n_event['invite_time']));
		$n_event['start_time'] = strtotime($date.' '.date("g:i a", $n_event['start_time']));


		// Check for duplicate events using place & time.
		$sql_query = 'SELECT * FROM '.$mConfig['table_events'].' WHERE location = '.$n_event['location'].' AND WHERE start_time = '.$n_event['start_time'];
		$sql_result = mysql_query($sql_query, $this->mul_db) or die('There was an error querying the event from Mullet.');
		$sql_rows = mysql_num_rows($sql_result);
		
		if ($sql_rows > 0) return FALSE;

		unset($sql_query); mysql_free_result($sql_result); unset($sql_rows);


		if (get_magic_quotes_gpc() == FALSE) $n_event['location'] = addslashes($n_event['location']);


		if ($n_event['isUpdate'] == FALSE)
		{
			$fields = 'event_id, location, invite_time, start_time, open, min_level, mt, ot, hl, dm, cap, mail_sent';
			$values = '
						"",
						"'.$n_event['location'].'",
						"'.$n_event['invite_time'].'",
						"'.$n_event['start_time'].'",
						1,
						'.$n_event['min_level'].',
						'.$n_event['mt'].',
						'.$n_event['ot'].',
						'.$n_event['hl'].',
						'.$n_event['dm'].',
						'.$n_event['cap'].',
						0';
			
			$sql_query = 'INSERT INTO '.$mConfig['table_events'].' ('.$fields.') VALUES ('.$values.')';
		}
		else
		{
			$set = '
					location = "'.$n_event['location'].'",
					invite_time = "'.$n_event['invite_time'].'",
					start_time = "'.$n_event['start_time'].'",
					min_level = '.$n_event['min_level'].',
					mt = '.$n_event['mt'].',
					ot = '.$n_event['ot'].',
					hl = '.$n_event['hl'].',
					dm = '.$n_event['dm'].',
					cap = '.$n_event['cap'].',
					mail_sent = '.$n_event['mail_sent'];
			
			$sql_query = 'UPDATE '.$mConfig['table_events'].' SET '.$set.' WHERE event_id='.$this->eid;
		}

		mysql_query($sql_query, $this->mul_db) or die('There was an error adding the event to Mullet.');
		
		// If a new event, get its ID.
		if ($n_event['isUpdate'] == FALSE) $this->eid = mysql_insert_id();
		
		// Update the class variables.
		if ($this->getEvent()) return TRUE;
		else return FALSE;
	}





	// Remove an event.
	function removeEvent()
	{
		global $mConfig;


		$sql_query = 'DELETE FROM '.$mConfig['table_events'].' WHERE event_id = '.$this->eid;
		mysql_query($sql_query, $this->mul_db) or die('There was an error removing the event from Mullet.');
		
		// Need to remove subscribers for this event.
		
		unset($sql_query);
	}





	// Open or close an event.
	function setEventStatus()
	{
		global $mConfig;


		$this->isOpen = !$this->isOpen;

		$sql_query = 'UPDATE '.$mConfig['table_events'].' SET open = '.$this->isOpen.' WHERE event_id = '.$this->eid;
		mysql_query($sql_query, $this->mul_db) or die('There was an error changing the status of the event.');
		
		unset($sql_query);
	}





	// Calculate slots remaining.
	function getSlots()
	{
		$this->getTotals();

		foreach ($mConfig['roles'] as $key => $value)
		{
			$remaining = $this->limits[$key] - $this->totals['attending'][$key];
			if ($remaining < 0) $remaining = 0;
			
			$this->slots[$key] = $remaining;
		}
	}





	// Get subscriber data
	function getSubscribers()
	{
		global $mConfig;

		unset($this->subscribers);
		$this->subscribers = array();

		$sql_query = 'SELECT * FROM '.$mConfig['table_subscriptions'].' WHERE event_id = '.$this->eid;
		$sql_result = mysql_query($sql_query, $this->mul_db) or die('There was an error querying event subscribers from Mullet. SQL: '.$sql_query);

		while ($sql_fetch = mysql_fetch_assoc($sql_result))
		{
			$tempSubscriber = new subscriber($this->mul_db, $this->smf_db, $sql_fetch['signup_id']);
			
			$this->subscribers[] = $tempSubscriber;
			
			unset($tempSubscriber);
		}
		
		unset($sql_query); mysql_free_result($sql_result); unset($sql_fetch);
	}





	// Sort user's characters that are subscribed or not subscribed.
	function userCharacterStatus($user)
	{
		$this->chars_subscribed['character'] = array();
		$this->chars_subscribed['role'] = array();
		$this->chars_subscribed['status'] = array();
		$this->chars_subscribed['comments'] = array();

		$user_info = array();

		foreach($this->subscribers as $subscriber)
		{
			if ($subscriber->uid == $_SESSION['mul_user_id'])
			{
				$user_info[$subscriber->char_name]['role'] = $subscriber->role;
				$user_info[$subscriber->char_name]['status'] = $subscriber->status;
				$user_info[$subscriber->char_name]['comments'] = $subscriber->comments;
			}
		}

		foreach ($user->characters as $char)
		{
			// This character is not signed up.
			if (array_key_exists(ucwords($char['name']), $user_info) == FALSE)
			{
				$this->chars_not_subscribed['character'][] = $char['name'];
				$this->chars_not_subscribed['role'][] = $char['role'];
			}
			
			// This character is signed up.
			else
			{
				$this->chars_subscribed['character'][] = $char['name'];
				$this->chars_subscribed['role'][] = $user_info[$char['name']]['role'];
				$this->chars_subscribed['status'][] = $user_info[$char['name']]['status'];
				$this->chars_subscribed['comments'][] = $user_info[$char['name']]['comments'];
			}
		}
	}





	// Count subscribers, classes and roles.
	function getTotals()
	{
		foreach($this->subscribers as $subscriber)
		{
			// Subscriber is marked for attendance.
			if ($subscriber->status == ATTENDING)
			{
				$this->totals['attending']['total']++;
				$this->totals['attending'][$subscriber->class]++;
				$this->totals['attending'][$subscriber->role]++;
			}

			// Subscriber is in the replacement queue.
			elseif ($subscriber->status == QUEUE)
			{
				$this->totals['queue']['total']++;
				$this->totals['queue'][$subscriber->class]++;
				$this->totals['queue'][$subscriber->role]++;
			}
			
			// Subscriber is unavailable.
			elseif ($subscriber->status == UNAVAILABLE)
			{
				$this->totals['unavailable']['total']++;
				$this->totals['unavailable'][$subscriber->class]++;
				$this->totals['unavailable'][$subscriber->role]++;
			}
			
			// Subscriber is available.
			else
			{
				$this->totals['available']['total']++;
				$this->totals['available'][$subscriber->class]++;
				$this->totals['available'][$subscriber->role]++;
			}


			// Totals
			$this->totals['subscribed']['total']++;
			$this->totals['subscribed'][$subscriber->class]++;
			$this->totals['subscribed'][$subscriber->role]++;
		}
	}




	function sendEventEmail()
	{
		global $mConfig;


		$tag = date("mdY");
		$bcc = '';
		$headers = 'From: webmaster@shinsei-guild.org'."\r\n".
		    	'Reply-To: webmaster@shinsei-guild.org'."\r\n".
		    	'X-Mailer: PHP/'.phpversion();

		$subject = $this->location.' - '.date("n/j/Y", $this->start_time);
		$body = '
		This is a reminder e-mail that you are scheduled as attending an upcoming event on MULLET.

		Event: '.$this->location.'
		Date/Time: '.date("n/j/Y \@ g:i a", $this->start_time).' PT
		Invite Time: '.date("g:i a", $this->invite_time).' PT

		Please see MULLET at www.shinsei-guild.org/mullet for event information.
		For more on guild raids: http://www.shinsei-guild.org/forums/index.php?topic=2288.0

		If there is a scheduling problem, please contact Zagron.
		(http://www.shinsei-guild.org/forums/index.php?action=pm;sa=send;u=34)


		--
		## '.$tag;


		// Get subscriber e-mail addresses
		for ($i = 0; $i < $subscribers; $i++);
		{
			if ($bcc == '') $bcc = $subscribers[$i]->email;
			else $bcc .= ', '.$subscribers[$i]->email;
		}


		// Update header to include address and send e-mail.
		$headers .= 'Bcc: '.$bcc."\r\n";
		mail('', $subject, $body, $headers);

		// Increment mail sent counter.
		$sql_query = 'UPDATE '.$mConfig['table_events'].' SET mail_sent = mail_sent + 1 WHERE event_id = '.$this->eid;
		mysql_query($sql_query, $this->mul_db) or die('There was an error adjusting the event announcement counter.');
		
		unset($sql_query);
		
		$this->mail_sent++;
	}
}
?>